<template>
  <el-form label-width="98" style="padding: 30px 0" scroll-to-error>
    <el-form-item label="SPU名称">
      <el-input placeholder="请输入SPU名称" v-model="spuParams.spuName" />
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select placeholder="请选择品牌" v-model="spuParams.tmId">
        <el-option
          v-for="tdm in spuTradeMarkList"
          :key="tdm.id"
          :value="tdm.id"
          :label="tdm.tmName"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type="textarea"
        placeholder="请输入SPU描述"
        v-model="spuParams.description"
        clearable
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图标">
      <el-upload
        v-model:file-list="ImageWallList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="beforeUpload"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img
          w-full="true"
          :src="dialogImageUrl"
          alt="Preview Image"
          width="400px"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select
        :placeholder="
          deffect ? `还有${deffect.length}个属性未选择` : '暂无数据可选择'
        "
        v-model="saleAttrId"
      >
        <el-option
          v-for="itemsale in deffect"
          :key="itemsale.id"
          :label="itemsale.name"
          :value="`${itemsale.id}:${itemsale.name}`"
        ></el-option>
      </el-select>
      <el-button
        type="primary"
        icon="Plus"
        size="default"
        :disabled="!saleAttrId"
        style="margin-left: 10px"
        @click="addSaleAttr"
      >
        添加属性
      </el-button>
      <el-table border style="margin: 10px 0" :data="SaleSpuAttrList">
        <el-table-column
          label="序号"
          type="index"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          label="属性名"
          prop="saleAttrName"
          align="center"
        ></el-table-column>
        <el-table-column
          label="属性值"
          prop="spuSaleAttrValueList"
          align="center"
        >
          <template #default="{ row, $index }">
            <el-tag
              type="warning"
              v-for="item in row.spuSaleAttrValueList"
              :key="item.id"
              style="margin: 0 5px"
              closable
              :disable-transitions="true"
              @close="row.spuSaleAttrValueList.splice($index, 1)"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              aria-placeholder="请输入属性值"
              v-if="row.flag"
              v-focus
              clearable
              size="small"
              v-model.trim="row.saleAttrValueName"
              @blur="addAttrValue(row)"
            />
            <el-button
              size="small"
              icon="Plus"
              @click="editGo(row)"
              v-else
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center">
          <template #default="{ $index }">
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click="SaleSpuAttrList.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button
        :disabled="deffect.length == 3"
        type="primary"
        size="default"
        icon="Select"
        @click="onSave"
      >
        保存
      </el-button>
      <el-button size="default" @click="candel()" icon="CloseBold">
        取消
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup name="spuForm">
import {
  addSpu,
  getSaleAttrSelect,
  getSaleSpuAttr,
  getSpuImageWall,
  getSpuTradeMark,
} from '@/api/product/spu'
import type {
  ImageWall,
  SaleAttrSelectData,
  SpuList,
  SpuTradeMark,
  spuSaleAttrData,
} from '@/api/product/spu/type'
import { ElMessage, UploadProps } from 'element-plus'
import { computed, ref } from 'vue'
const emit = defineEmits(['sen'])
let spuTradeMarkList = ref<SpuTradeMark[]>([])
let ImageWallList = ref<ImageWall[]>([])
let SaleSpuAttrList = ref<spuSaleAttrData[]>([])
let SaleSelectList = ref<SaleAttrSelectData[]>([])
let dialogImageUrl = ref('')
let dialogVisible = ref(false)
let spuParams = ref<SpuList>({
  spuName: '',
  description: '',
  category3Id: '',
  tmId: '',
  spuSaleAttrList: [],
  spuImageList: [],
})
//初始化form表单数据
const clearnForm = () => {
  Object.assign(spuParams.value, {
    spuName: '',
    description: '',
    category3Id: '',
    tmId: '',
    spuSaleAttrList: [],
    spuImageList: [],
  })
  SaleSpuAttrList.value = []
  saleAttrId.value = ''
  ImageWallList.value = []
}
let saleAttrId = ref()
//定义一个方法用于被父组件触发初始化修改页面的数据和添加的初始数据
const onLoaded = async (row: SpuList) => {
  // 初始化表单数据
  clearnForm()
  //初始化原始数据，把原有数据携带过来
  spuParams.value = row
  //获取所有品牌信息用于下拉框选择
  let tMresult = await getSpuTradeMark()
  if (tMresult.code == 200) spuTradeMarkList.value = tMresult.data
  //获取image照片墙列表
  let imgResult = await getSpuImageWall(row.id as number)
  //格式化数组给照片墙组件使用
  if (imgResult.code == 200) {
    ImageWallList.value = imgResult.data.map((item) => {
      return {
        name: item.imgName,
        url: item.imgUrl,
      }
    })
  }
  // 获取已有的属性属性值列表
  let attrResult = await getSaleSpuAttr(row.id as number)
  if (attrResult.code == 200) SaleSpuAttrList.value = attrResult.data
  //获取全部属性值
  let allAttrresult = await getSaleAttrSelect()
  if (allAttrresult.code == 200) SaleSelectList.value = allAttrresult.data
}
//定义一个方法用于被父组件触发初始化和添加的初始数据
const addLoaded = async (c3Id: number) => {
  // 初始化表单数据
  clearnForm()
  //把三级分类id赋值给数组
  spuParams.value.category3Id = c3Id
  //获取所有品牌信息用于下拉框选择
  let tMresult = await getSpuTradeMark()
  if (tMresult.code == 200) spuTradeMarkList.value = tMresult.data
  //获取全部属性值
  let allAttrresult = await getSaleAttrSelect()
  if (allAttrresult.code == 200) SaleSelectList.value = allAttrresult.data
}
//小窗查看
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const handleRemove: UploadProps['onRemove'] = () => {}
//添加前校验
const beforeUpload = (rawFile: any) => {
  if (
    rawFile.type == 'image/jepg' ||
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 > 10) {
      ElMessage({
        type: 'error',
        message: '文件不能大于10MB',
      })
      return false
    } else {
      return true
    }
  } else {
    ElMessage({
      type: 'warning',
      message: '图片格式jpeg/png/gif',
    })
    return false
  }
}
//every结合filter过滤两个数组对象中不同的值!!!!!!!!!!!!
const deffect = computed(() =>
  SaleSelectList.value.filter((item) =>
    SaleSpuAttrList.value.every((ite) => ite.saleAttrName != item.name),
  ),
)
//取消添加
const candel = () => {
  emit('sen', { flag: 0, params: '' })
}
// 添加销售属性
const addSaleAttr = () => {
  //把下拉框value的值从字符串中取出来
  const [baseSaleAttrId, saleAttrName] = saleAttrId.value.split(':')
  // 创建一个新的对象用来收集数据
  let newAttr: spuSaleAttrData = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }
  //追加到数组的最后面
  SaleSpuAttrList.value.push(newAttr)
  saleAttrId.value = ''
}
//去编辑！！！！编辑模式的切换
const editGo = (row: spuSaleAttrData) => {
  row.flag = true
}
//添加新的属性值
const addAttrValue = (row: spuSaleAttrData) => {
  const { baseSaleAttrId, saleAttrValueName } = row
  //防止用户输入非法数据，输入非法数据就不往下执行等代用户填写完再往下执行
  if (saleAttrValueName) {
    let repeat = row.spuSaleAttrValueList.find((item) => {
      return saleAttrValueName == item.saleAttrValueName
    })
    if (repeat) {
      ElMessage({ type: 'warning', message: '数据重复' })
      return
    }
    row.spuSaleAttrValueList.push({
      baseSaleAttrId: baseSaleAttrId,
      saleAttrValueName: saleAttrValueName!,
    })
  } else {
    ElMessage({ type: 'error', message: '不能为空' })
  }
  row.flag = false
  row.saleAttrValueName = ''
}
const onSave = async () => {
  //用map重新定义数据结构
  spuParams.value.spuImageList = ImageWallList.value.map((item: any) => {
    return {
      imgName: item.name,
      //&&两边结果必须是都为true才会可以当item。response不存在的时候左边结果就是false就会去看||后面的结果
      imgUrl: (item.response && item.response.data) || item.url,
    }
  })
  //提取SaleSpuAttrList到spuParams
  spuParams.value.spuSaleAttrList = SaleSpuAttrList.value
  const result = await addSpu(spuParams.value)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '保存成功' })
    // 切换场景
    emit('sen', { flag: 0, params: spuParams.value.id ? 'update' : 'add' })
  } else {
    ElMessage({ type: 'error', message: '保存失败' + result.code })
  }
}
const vFocus = {
  mounted(el: HTMLElement) {
    el.querySelector('input')!.focus()
  },
}
//向外暴露
defineExpose({ onLoaded, addLoaded })
</script>
<style scoped>
.el-select {
  width: 20%;
}
.el-input {
  width: 80%;
}
</style>
